package com.aiti.lulian.service;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.entity.ShowActivityInfo;
import com.aiti.lulian.entity.SysArea;
import com.aiti.lulian.gxmh.util.JsoupUtils;
import com.aiti.lulian.mapper.SysAreaMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class SearchService {

    private static final String HOST = "http://www.eshow365.com";

    private static final String ABROAD_URL = "http://www.eshow365.com/ZhanHui/Ajax/AjaxWaiZhanSearcherV3.aspx?1=1&areano=35&tag=0&fangwenindex=0&page=%s";

    private static final String INTERNAL_URL = "http://www.eshow365.com/ZhanHui/Ajax/AjaxSearcherV3.aspx?1=1&tag=0&page=%s";

    private static final DateTimeFormatter INPUT_FORMAT = DateTimeFormatter.ofPattern("yyyy/M/d");
    private static final DateTimeFormatter OUTPUT_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private SysAreaMapper sysAreaMapper;

    public static void main(String[] args) {
        List<String> allUrlList = new ArrayList<>();
        List<ShowActivityInfo> activityList = new ArrayList<>();
        try {
            // 发起请求并获取文档
            Date latestDate = new Date();
            //String beginEndCondition = getBeginEndCondition(latestDate);
            String beginEndCondition = "&starttime=2025/07/01&startendtime=2025/07/31";
            String url = String.format(INTERNAL_URL + beginEndCondition, 1);
            log.info("准备请求的地址为："+ url);
            Document doc = JsoupUtils.getDocumentFromURL(url);
            // 2. 获取最大页数
            int maxPage = getAbroadMaxPage(doc);
            log.info("最大页数: " + maxPage);
            Thread.sleep(2000);
            parseInternalDocument(allUrlList, doc, maxPage,beginEndCondition);
            log.info("所有的url: " + allUrlList);
            int count = 0;
            for(String link : allUrlList){
                if (count > 10) {
                    break;
                }
                log.info("准备请求的详情url: " + link);
                Document detailDoc = JsoupUtils.getDocumentFromURL(link);
                try{
                    ShowActivityInfo activityInfo = parseDetail(detailDoc);
                    activityInfo.setDetailUrl(link);
                    activityList.add(activityInfo);
                    count++;
                } catch (Exception e) {
                    log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
                    continue;
                }

            }
            log.info("结果为："+activityList);
        } catch (Exception e) {
            log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
        }
    }

    public List<ShowActivityInfo> addInternalActivity(Date latestDate){
        List<String> allUrlList = new ArrayList<>();
        List<ShowActivityInfo> activityList = new ArrayList<>();
        try {
            // 发起请求并获取文档
            String beginEndCondition = getInternalBeginEndCondition(latestDate);
            //String beginEndCondition = "&starttime=2025/08/01&startendtime=2025/08/31";
            String url = String.format(INTERNAL_URL + beginEndCondition, 1);
            log.info("准备请求的地址为："+ url);
            Document doc = JsoupUtils.getDocumentFromURL(url);
            // 2. 获取最大页数
            int maxPage = getAbroadMaxPage(doc);
            log.info("最大页数: " + maxPage);
            Thread.sleep(3000);
            parseInternalDocument(allUrlList, doc, maxPage,beginEndCondition);
            log.info("所有的url: " + allUrlList);
            if(!CollectionUtils.isEmpty(allUrlList)){
                allUrlList = allUrlList.stream().distinct().collect(Collectors.toList());
            }
            for(String link : allUrlList){
                log.info("准备请求的详情url: " + link);
                Thread.sleep(2000);
                try{
                    Document detailDoc = JsoupUtils.getDocumentFromURL(link);
                    ShowActivityInfo activityInfo = parseDetail(detailDoc);
                    activityInfo.setFirstActivityType("国内活动");
                    activityInfo.setSecondActivityType("行业展会");
                    activityInfo.setDetailUrl(link);
                    activityInfo.setSource("1");
                    String city = activityInfo.getCity();
                    String province = activityInfo.getProvince();
                    if(!StringUtils.isEmpty(province)){
                        List<SysArea> areaCode = sysAreaMapper.selectList(new QueryWrapper<SysArea>().likeRight("base_name", province).eq("area_level", "1").isNull("base_parent_id"));
                        if(!CollectionUtils.isEmpty(areaCode)){
                            activityInfo.setProvince(areaCode.get(0).getBaseId());
                        }
                    }

                    if(!StringUtils.isEmpty(city)){
                        List<SysArea> areaCode = sysAreaMapper.selectList(new QueryWrapper<SysArea>().likeRight("base_name", city).eq("area_level", "2").isNotNull("base_parent_id"));
                        if(!CollectionUtils.isEmpty(areaCode)){
                            activityInfo.setCity(areaCode.get(0).getBaseId());
                        }
                    }


                    activityList.add(activityInfo);
                } catch (Exception e) {
                    log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
                    continue;
                }

            }
            log.info("结果为："+activityList);
        } catch (Exception e) {
            log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
        }
        return activityList;
    }

    public List<ShowActivityInfo> addAbroadActivity(Date latestDate){
        // 目标 URL
        List<String> allUrlList = new ArrayList<>();
        List<ShowActivityInfo> activityList = new ArrayList<>();
        try {
            // 发起请求并获取文档
            String beginEndCondition = getAbroadBeginEndCondition(latestDate);
            String url = String.format(ABROAD_URL + beginEndCondition, 1);
            log.info("准备请求的地址为："+ url);
            Document doc = JsoupUtils.getDocumentFromURL(url);
            // 2. 获取最大页数
            int maxPage = getAbroadMaxPage(doc);
            log.info("最大页数: " + maxPage);
            Thread.sleep(2000);
            parseAbroadDocument(allUrlList, doc, maxPage, beginEndCondition);
            log.info("所有的url: " + allUrlList);
            if(!CollectionUtils.isEmpty(allUrlList)){
                allUrlList = allUrlList.stream().distinct().collect(Collectors.toList());
            }
            for(String link : allUrlList){
                Thread.sleep(2000);
                log.info("准备请求的详情url: " + link);
                try{
                    Document detailDoc = JsoupUtils.getDocumentFromURL(link);
                    ShowActivityInfo activityInfo = parseDetail(detailDoc);
                    activityInfo.setFirstActivityType("海外活动");
                    activityInfo.setSecondActivityType("海外展会");
                    activityInfo.setDetailUrl(link);
                    activityInfo.setSource("1");
                    activityList.add(activityInfo);
                } catch (Exception e) {
                    log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
                    continue;
                }

            }
            log.info("结果为："+activityList);
        } catch (Exception e) {
            log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
        }
        return activityList;
    }

    private static String getInternalBeginEndCondition(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        // 当前日期
        Calendar now = Calendar.getInstance();
        log.info("当前日期: " + sdf.format(now.getTime()));


        Calendar targetBeginMonth = (Calendar) now.clone();
        targetBeginMonth.add(Calendar.MONTH, 1);


        targetBeginMonth.set(Calendar.DAY_OF_MONTH, 1);
        Date startDate = targetBeginMonth.getTime();

        // 获取这个月的最后一天
        Calendar targetEndMonth = (Calendar) now.clone();
        targetEndMonth.add(Calendar.MONTH, 1);
        int lastDay = targetEndMonth.getActualMaximum(Calendar.DAY_OF_MONTH);
        targetEndMonth.set(Calendar.DAY_OF_MONTH, lastDay);
        Date endDate = targetEndMonth.getTime();
        String startTime = sdf.format(startDate);
        String endTime = sdf.format(endDate);
        // 输出
        log.info("开始时间: " + startTime);
        log.info("结束时间: " + endTime);
        return String.format("&starttime=%s&startendtime=%s", startTime, endTime);
    }

    private static String getAbroadBeginEndCondition(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        // 当前日期
        Calendar now = Calendar.getInstance();
        log.info("当前日期: " + sdf.format(now.getTime()));


        Calendar targetBeginMonth = (Calendar) now.clone();
        targetBeginMonth.add(Calendar.MONTH, 1);


        targetBeginMonth.set(Calendar.DAY_OF_MONTH, 1);
        Date startDate = targetBeginMonth.getTime();

        // 获取这个月的最后一天
        Calendar targetEndMonth = (Calendar) now.clone();
        targetEndMonth.add(Calendar.MONTH, 6);
        int lastDay = targetEndMonth.getActualMaximum(Calendar.DAY_OF_MONTH);
        targetEndMonth.set(Calendar.DAY_OF_MONTH, lastDay);
        Date endDate = targetEndMonth.getTime();
        String startTime = sdf.format(startDate);
        String endTime = sdf.format(endDate);
        // 输出
        log.info("开始时间: " + startTime);
        log.info("结束时间: " + endTime);
        return String.format("&starttime=%s&startendtime=%s", startTime, endTime);
    }

    public static void parseInternalDocument(List<String> allUrlList, Document doc, int maxPage, String beginEndCondition) {



        // 3. 处理当前页的列表内容
        List<String> urlList = processInternalCurrentPage(doc);
        log.info("提取到的链接数量: " + urlList.size());
        log.info("链接列表: " + urlList);
        allUrlList.addAll(urlList);
        if(maxPage > 1){
            for(int page = 2; page<= maxPage; page++){

                try{
                    Document nextPageDoc = JsoupUtils.getDocumentFromURL(String.format(INTERNAL_URL+beginEndCondition, page));
                    Thread.sleep(2000);
                    List<String> nextPageUrlList = processInternalCurrentPage(nextPageDoc);
                    log.info("提取到的第"+page+"页链接数量: " + nextPageUrlList.size());
                    log.info("提取到的第"+page+"页链接列表: " + nextPageUrlList);
                    allUrlList.addAll(nextPageUrlList);
                } catch (Exception e) {
                    log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
                    continue;
                }
            }
        }
    }

    public static List<String> processInternalCurrentPage(Document doc) {
        List<String> links = new ArrayList<>();

        // 定位所有 class="sslist" 的列表项
        Elements sslistItems = doc.select("div.sslist");

        // 如果没有找到列表项，直接返回空列表
        if (sslistItems.isEmpty()) {
            return links;
        }

        // 遍历每个列表项
        for (Element item : sslistItems) {
            // 在列表项中查找 class="zhtitle" 的元素
            Element zhtitle = item.selectFirst("p.zhtitle");
            if (zhtitle != null) {
                // 在 zhtitle 中查找 <a> 标签
                Element link = zhtitle.selectFirst("a");
                if (link != null) {
                    String href = link.attr("href").trim();

                    if (href != null && href.startsWith("/")) {
                        links.add(HOST+href);
                    }
                }
            }
        }
        return links;
    }





    public static void parseAbroadDocument(List<String> allUrlList, Document doc, int maxPage, String beginEndCondition) {


        // 3. 处理当前页的列表内容
        List<String> urlList = processAbroadCurrentPage(doc);
        log.info("提取到的链接数量: " + urlList.size());
        log.info("链接列表: " + urlList);
        allUrlList.addAll(urlList);
        if(maxPage > 1){
            for(int page = 2; page<= maxPage; page++){

                try{
                    Document nextPageDoc = JsoupUtils.getDocumentFromURL(String.format(ABROAD_URL+beginEndCondition, page));
                    Thread.sleep(2000);
                    List<String> nextPageUrlList = processAbroadCurrentPage(nextPageDoc);
                    log.info("提取到的第"+page+"页链接数量: " + nextPageUrlList.size());
                    log.info("提取到的第"+page+"页链接列表: " + nextPageUrlList);
                    allUrlList.addAll(nextPageUrlList);
                } catch (Exception e) {
                    log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
                    continue;
                }
            }
        }
    }



    private static ShowActivityInfo parseDetail(Document doc) throws ParseException {

        // 1. 提取展会标题
        String title = doc.select("h1").first().text().trim();

        // 2. 提取展会Logo
        Element logoElement = doc.select("div.zhtitlepic img").first();
        String logoUrl = logoElement != null ? HOST + logoElement.attr("src") : "";

        // 3. 提取展会时间和地址
        String timeRange = "";
        String address = "";
        Elements zhxxElements = doc.select("div.zhxxcontent > p");
        for (Element p : zhxxElements) {
            String text = p.text().trim();
            if (text.startsWith("举办时间：")) {
                timeRange = text.replace("举办时间：", "");
            } else if (text.startsWith("举办展馆：")) {
                address = text.replace("举办展馆：", "").replace("&nbsp;", "").replace("乘车路线", "").trim();
            }
        }

        // 处理时间格式
        String startTime = "";
        String endTime = "";
        if (!timeRange.isEmpty()) {
            String[] dates = timeRange.split("---");
//            if (dates.length == 2) {
//                try {
//
//
//                    Date startDate = INPUT_FORMAT.parse(dates[0].trim());
//                    Date endDate = INPUT_FORMAT.parse(dates[1].trim());
//
//                    startTime = OUTPUT_FORMAT.format(startDate);
//                    endTime = OUTPUT_FORMAT.format(endDate);
//                } catch (Exception e) {
//                    log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
//                }
//            }
            if (dates.length == 2) {
                try {
                    LocalDate startDate = LocalDate.parse(dates[0].trim(), INPUT_FORMAT);
                    LocalDate endDate = LocalDate.parse(dates[1].trim(), INPUT_FORMAT);

                    startTime = startDate.format(OUTPUT_FORMAT);
                    endTime = endDate.format(OUTPUT_FORMAT);

                    log.info("Start Time: " + startTime);
                    log.info("End Time: " + endTime);

                } catch (Exception e) {
                    log.error("失败原因：{}", ExceptionUtil.stacktraceToString(e));
                }
            }
        }

        // 4. 提取展会简介
        String introduction = "";
        // 先找到包含"展会简介"标题的div
//        for (Element div : doc.select("div.zhgk")) {
//            Element span = div.select("h4 > span").first();
//            if (span != null && "展会简介".equals(span.text().trim())) {
//                Element introDiv = div.select("div.zhgkcon").first();
//                if (introDiv != null) {
//                    // 获取所有文本节点内容
//                    introduction = introDiv.text().trim();
//                    break;
//                }
//            }
//        }

        Elements zhgkElements = doc.select("div.zhgk");

        if (!zhgkElements.isEmpty()) {
            // 获取第一个zhgk元素下的zhgkcon
            Element zhgkcon = zhgkElements.first().select("div.zhgkcon").first();

            if (zhgkcon != null) {
                // 提取完整HTML内容（包括自身标签）
                introduction = zhgkcon.outerHtml();
                log.info("提取结果:\n" + introduction);

            } else {
                log.info("未找到简介对应的zhgkcon元素");
            }
        } else {
            log.info("未找到简介对应的zhgk元素");
        }

        // 1. 定位到zhxxcontent元素
        Element zhxxcontent = doc.selectFirst("div.zhxxcontent");
        if (zhxxcontent == null) {
            log.error("未找到zhxxcontent元素");

        }

        // 2. 找到包含"展会城市："的<p>标签
        Elements cityElements = zhxxcontent.select("p:contains(展会城市：)");
        if (cityElements.isEmpty()) {
            log.error("未找到展会城市信息");

        }

        // 3. 提取城市文本并解析
        String cityText = cityElements.first().ownText();
        // 示例格式："展会城市：国外|德国" 或 "展会城市：浙江|杭州市"
        String cityInfo = cityText.replace("展会城市：", "").trim();

        // 4. 分割省份和城市
        String[] parts = cityInfo.split("\\|");
        if (parts.length < 2) {
            log.error("城市信息格式不正确: " + cityInfo);

        }

        String province = parts[0].trim();
        String city = parts[1].trim();



        log.info("省份: " + province);
        log.info("城市: " + city);

        // 打印结果
        log.info("展会标题: " + title);
        log.info("Logo URL: " + logoUrl);
        log.info("开始时间: " + startTime);
        log.info("结束时间: " + endTime);
        log.info("展会地址: " + address);
        log.info("展会简介: " + introduction);
        ShowActivityInfo activityInfo = new ShowActivityInfo();
        activityInfo.setBaseName(title);
        activityInfo.setPic(logoUrl);
        activityInfo.setBeginTime(DATE_FORMAT.parse(startTime));
        activityInfo.setEndTime(DATE_FORMAT.parse(endTime));
        activityInfo.setAddress(address);
        activityInfo.setDescription(introduction);
        activityInfo.setStartEnrollFlag(false);
        activityInfo.setProvince(province);
        activityInfo.setCity(city);

        return activityInfo;
    }


    // 获取最大页数
    private static int getAbroadMaxPage(Document doc) {
        // 从分页控件中获取尾页的rel值（最大页数）
        Element lastPageLink = doc.selectFirst("li.nextlast a:last-child");
        if (lastPageLink != null) {
            String relValue = lastPageLink.attr("rel");
            try {
                return Integer.parseInt(relValue);
            } catch (NumberFormatException e) {
                // 备用方案：从分页下拉框获取最大值
                Elements pageOptions = doc.select("select.pagetiao option");
                if (!pageOptions.isEmpty()) {
                    String lastOptionValue = pageOptions.last().attr("value");
                    return Integer.parseInt(lastOptionValue);
                }
            }
        }
        return 1; // 默认只有1页
    }

    // 处理当前页内容
    private static List<String> processAbroadCurrentPage(Document doc) {
        List<String> urlList = new ArrayList<>();

        // 查找列表容器
        Element sslistContainer = doc.selectFirst("div.sbody");
        if (sslistContainer == null) {
            return urlList; // 没有列表容器
        }

        // 获取所有列表项（排除表头）
        Elements sslistItems = sslistContainer.select("div.sslist:not(.sslisthead)");
        if (sslistItems.isEmpty()) {
            return urlList; // 没有列表项
        }

        // 提取每个列表项中的链接
        for (Element item : sslistItems) {
            Element titleLink = item.selectFirst("p.zhtitle a");
            if (titleLink != null) {
                String href = titleLink.attr("href");
                if (!href.isEmpty()) {
                    urlList.add(HOST + href);
                }
            }
        }

        return urlList;
    }
}
